package com.qf.agro.service.facilities.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.agro.common.CustomerException;
import com.qf.agro.common.SysUserHolder;
import com.qf.agro.facilities.Facilities;
import com.qf.agro.mapper.FacilitiesMapper;
import com.qf.agro.service.facilities.FacilitiesService;
import com.qf.agro.vo.OptionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @company：千锋教育
 * @author：zhy
 * @date：2023/7/3
 */
@Service
public class FacilitiesServiceImpl implements FacilitiesService {

    @Autowired
    private FacilitiesMapper facilitiesMapper;


    @Override
    public Page<Facilities> findPage(Integer pageNum, Integer pageSize, String name) {
        //1.设置分页信息
        Page<Facilities> page = new Page<>(pageNum,pageSize);
        //2.创建查询条件
        LambdaQueryWrapper<Facilities> queryWrapper = new LambdaQueryWrapper<>();
        //3.设置条件
        queryWrapper.like(name != null,Facilities::getCategoryName,name);
        //查询企业自己的农业设施
        queryWrapper.eq(Facilities::getCompanyId, SysUserHolder.get().getCompanyId());
        //4.查询
        page = facilitiesMapper.selectPage(page,queryWrapper);
        //5.返回
        return page;
    }

    @Override
    public void save(Facilities facilities) {
        facilitiesMapper.insert(facilities);
    }

    @Override
    public void update(Facilities facilities) {
        facilitiesMapper.updateById(facilities);
    }

    @Override
    public void delete(Long id) {
        //1.先要使用分类id，查询看看有没有农业设施再用
        QueryWrapper<Facilities> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("count(*)");//投影查询
        queryWrapper.eq("category_id",id);
        Integer count = facilitiesMapper.selectCount(queryWrapper);
        //2.如果有的话，不能删除
        if(count > 0){
            //有，不能删除
            throw new CustomerException("有农业设施正在使用此分类，不能删除");
        }
        //3.没有的话，再删除
        facilitiesMapper.deleteById(id);
    }

    @Override
    public List<OptionVo> selectOptions() {
        return facilitiesMapper.selectOptions();
    }
}
